<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
            v-model="queryParams.goodsName"
            placeholder="请输入商品名称搜索"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类别" prop="goodsType">
        <el-input
            v-model="queryParams.goodsType"
            placeholder="请输入商品类别搜索"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="goodsStatus">
        <el-select
            v-model="queryParams.goodsStatus"
            placeholder="请选择状态搜索"
            clearable
            @change="handleQuery"
            style="width: 100%"
            :filterable="true">
          <el-option v-for="(item, index) in goodsStatusOptions"
                     :key="index"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['order:goods:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['order:goods:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['order:goods:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['order:goods:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品编号" align="center" prop="goodsId"/>
      <el-table-column label="商品图片" align="center" prop="goodsImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.goodsImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="goodsName"/>
      <el-table-column label="商品类别" align="center" prop="goodsType"/>
      <el-table-column label="一口价" align="center" prop="goodsPrice"/>
      <el-table-column label="包装费" align="center" prop="goodsPackage"/>
      <el-table-column label="状态" align="center" prop="goodsStatus">
        <template #default="scope">
          {{ formatGoodsStatus(scope.row.goodsStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="已售出数量" align="center" prop="number"/>
      <el-table-column label="创建时间" align="center" prop="goodsCreateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.goodsCreateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"
                     icon="Edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['order:goods:edit']"
          >修改
          </el-button>
          <el-button link type="primary"
                     icon="Delete"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['order:goods:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script setup name="Goods">
// import {listGoods, getGoods, delGoods, addGoods, updateGoods} from "@/api/order/goods"
import {listGoods, delGoods} from "@/api/order/goods"
import {useRouter} from "vue-router";

import {goodsStatusOptions, formatGoodsStatus} from "@/views/order/goods/utils.js";
import {onMounted} from "vue";
import {listGoodsByShopId} from "@/api/order/goods";

const router = useRouter()

const {proxy} = getCurrentInstance()

const goodsList = ref([])
// const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
// const title = ref("")

const data = reactive({
  // form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopId: null,
    goodsType: null,
    goodsDesc: null,
    goodsCreateTime: null,
    goodsName: null,
    goodsImage: null,
    goodsPrice: null,
    goodsPackage: null,
    goodsStatus: undefined,
    recommend: null,
    stock: null,
    number: null
  },
  // rules: {
  //   shopId: [
  //     {required: true, message: "店铺id不能为空", trigger: "blur"}
  //   ],
  //   goodsName: [
  //     {required: true, message: "商品名称不能为空", trigger: "blur"}
  //   ],
  //   goodsStatus: [
  //     {required: true, message: "请选择状态", trigger: "change"}
  //   ]
  // }
})

// const {queryParams, form, rules} = toRefs(data)
const {queryParams} = toRefs(data)

/** 查询商品列表列表 */
function getList() {
  loading.value = true
  // listGoods(queryParams.value).then(response => {
  //   goodsList.value = response.rows
  //   total.value = response.total
  //   loading.value = false
  // })
  listGoodsByShopId(0).then(response => {
    goodsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
// function cancel() {
//   open.value = false
//   reset()
// }

// 表单重置
// function reset() {
//   form.value = {
//     goodsId: null,
//     shopId: null,
//     goodsType: null,
//     goodsDesc: null,
//     goodsCreateTime: null,
//     goodsName: null,
//     goodsImage: null,
//     goodsPrice: null,
//     goodsPackage: null,
//     goodsStatus: null,
//     recommend: null,
//     stock: null,
//     number: null
//   }
//   proxy.resetForm("goodsRef")
// }

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.goodsId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  router.push('/order/goods/edit')
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const goodsId = row.goodsId || ids.value[0]
  router.push(`/order/goods/edit/${goodsId}`)
}

/** 提交按钮 */
// function submitForm() {
//   proxy.$refs["goodsRef"].validate(valid => {
//     if (valid) {
//       if (form.value.goodsId != null) {
//         updateGoods(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功")
//           open.value = false
//           getList()
//         })
//       } else {
//         addGoods(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功")
//           open.value = false
//           getList()
//         })
//       }
//     }
//   })
// }

/** 删除按钮操作 */
function handleDelete(row) {
  const _goodsIds = row.goodsId || ids.value
  proxy.$modal.confirm('是否确认删除商品列表编号为"' + _goodsIds + '"的数据项？').then(function () {
    return delGoods(_goodsIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/goods/export', {
    ...queryParams.value
  }, `goods_${new Date().getTime()}.xlsx`)
}

onMounted(() =>{
  // 监听路由变化，当从编辑页返回数据时刷新数据
  const unwatch = router.afterEach((to, from) => {
    if(from.path.startsWith('/order/goods/edit') && to.path === '/goodsManagement/goods'){
      getList()
    }
  })
})

getList()
</script>
